package com.study.javaFx.view;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.study.javaFx.model.Lab;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class LabView {
    // HTTP客户端和JSON工具
    private final HttpClient httpClient = HttpClient.newHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
    // 后端基础URL
    private final String BASE_URL = "http://localhost:8080/api/lab";

    /**
     * 显示查询机房的窗口
     */
    public void showQueryWindow() {
        Stage stage = new Stage();
        stage.setTitle("查询机房");

        TableView<Lab> table = new TableView<>();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn<Lab, Number> idCol = new TableColumn<>("ID");
        idCol.setCellValueFactory(cellData -> cellData.getValue().labIdProperty());
        TableColumn<Lab, String> nameCol = new TableColumn<>("机房名称");
        nameCol.setCellValueFactory(cellData -> cellData.getValue().labNameProperty());
        TableColumn<Lab, String> locationCol = new TableColumn<>("位置");
        locationCol.setCellValueFactory(cellData -> cellData.getValue().locationProperty());
        TableColumn<Lab, Number> capacityCol = new TableColumn<>("容量");
        capacityCol.setCellValueFactory(cellData -> cellData.getValue().capacityProperty());
        table.getColumns().addAll(idCol, nameCol, locationCol, capacityCol);

        // 查询输入区
        GridPane queryPane = new GridPane();
        queryPane.setPadding(new Insets(10));
        queryPane.setHgap(10);
        queryPane.setVgap(10);
        queryPane.add(new Label("输入ID列表(逗号分隔):"), 0, 0);
        TextField idsField = new TextField();
        queryPane.add(idsField, 1, 0);
        Button queryBtn = new Button("查询");
        queryPane.add(queryBtn, 2, 0);

        // 初始自动加载所有机房数据
        HttpRequest allRequest = HttpRequest.newBuilder().uri(URI.create(BASE_URL + "/get")).GET().build();
        httpClient.sendAsync(allRequest, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
                .thenApply(HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        System.out.println("后端返回原始数据: " + json); // 打印原始JSON
                        // 解析后端返回的Response<List<Lab>>
                        JsonNode node = objectMapper.readTree(json);
                        JsonNode dataNode = node.get("data");
                        List<Lab> labs = objectMapper.readValue(dataNode.traverse(), new TypeReference<List<Lab>>(){});
                        ObservableList<Lab> data = FXCollections.observableArrayList(labs);
                        Platform.runLater(() -> table.setItems(data));
                    } catch (Exception ex) {
                        System.out.println("JSON解析异常: " + ex.getMessage()); // 打印异常信息
                        Platform.runLater(() -> showAlert("初始化数据失败: " + ex.getMessage()));
                    }
                })
                .exceptionally(ex -> { System.out.println("初始化请求异常: " + ex.getMessage()); Platform.runLater(() -> showAlert("初始化请求失败: " + ex.getMessage())); return null; });

        queryBtn.setOnAction(e -> {
            String idsText = idsField.getText().trim();
            // 边界判断：不能为空
            if (idsText.isEmpty()) {
                showAlert("请输入要查询的ID列表");
                return;
            }
            // 边界判断：每个ID必须为正整数
            String[] idArr = idsText.split(",");
            for (String idStr : idArr) {
                idStr = idStr.trim();
                if (idStr.isEmpty()) {
                    showAlert("ID列表中存在空值");
                    return;
                }
                try {
                    int id = Integer.parseInt(idStr);
                    if (id <= 0) {
                        showAlert("ID必须为正整数");
                        return;
                    }
                } catch (Exception ex) {
                    showAlert("ID必须为数字");
                    return;
                }
            }
            // 只支持单个id查询
            String id = idArr[0].trim();
            String url = BASE_URL + "/get/" + id;
            HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
            httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
                    .thenApply(HttpResponse::body)
                    .thenAccept(json -> {
                        try {
                            System.out.println("后端返回原始数据: " + json); // 打印原始JSON
                            // 解析后端返回的Response<Lab>
                            JsonNode node = objectMapper.readTree(json);
                            JsonNode dataNode = node.get("data");
                            Lab lab = objectMapper.readValue(dataNode.traverse(), Lab.class);
                            List<Lab> labs = new ArrayList<>();
                            if (lab != null) labs.add(lab);
                            ObservableList<Lab> data = FXCollections.observableArrayList(labs);
                            Platform.runLater(() -> table.setItems(data));
                        } catch (Exception ex) {
                            System.out.println("JSON解析异常: " + ex.getMessage()); // 打印异常信息
                            Platform.runLater(() -> showAlert("解析数据失败: " + ex.getMessage()));
                        }
                    })
                    .exceptionally(ex -> { System.out.println("请求异常: " + ex.getMessage()); Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        VBox vbox = new VBox(queryPane, table);
        vbox.setPadding(new Insets(10));
        Scene scene = new Scene(vbox, 500, 350);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示新增机房的窗口
     */
    public void showAddWindow() {
        Stage stage = new Stage();
        stage.setTitle("新增机房");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("名称:"), 0, 0);
        TextField nameField = new TextField();
        grid.add(nameField, 1, 0);
        grid.add(new Label("位置:"), 0, 1);
        TextField locationField = new TextField();
        grid.add(locationField, 1, 1);
        grid.add(new Label("容量:"), 0, 2);
        TextField capacityField = new TextField();
        grid.add(capacityField, 1, 2);

        Button submitBtn = new Button("提交");
        submitBtn.setOnAction(e -> {
            String name = nameField.getText().trim();
            String location = locationField.getText().trim();
            String capacityStr = capacityField.getText().trim();
            if (name.isEmpty() || location.isEmpty() || capacityStr.isEmpty()) {
                showAlert("请填写所有字段");
                return;
            }
            int capacity;
            try {
                capacity = Integer.parseInt(capacityStr);
                if (capacity <= 0) {
                    showAlert("容量必须为正整数");
                    return;
                }
            } catch (Exception ex) {
                showAlert("容量必须为数字");
                return;
            }
            Lab lab = new Lab(0, name, location, capacity);
            try {
                String json = objectMapper.writeValueAsString(lab);
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(BASE_URL + "/add"))
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(HttpResponse::body)
                        .thenAccept(resp -> showInfoDialog("新增成功！"))
                        .exceptionally(ex -> { showAlert("请求失败: " + ex.getMessage()); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 3);
        Scene scene = new Scene(grid, 350, 200);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示修改机房的窗口
     */
    public void showUpdateWindow() {
        Stage stage = new Stage();
        stage.setTitle("修改机房");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("机房ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);
        grid.add(new Label("名称:"), 0, 1);
        TextField nameField = new TextField();
        grid.add(nameField, 1, 1);
        grid.add(new Label("位置:"), 0, 2);
        TextField locationField = new TextField();
        grid.add(locationField, 1, 2);
        grid.add(new Label("容量:"), 0, 3);
        TextField capacityField = new TextField();
        grid.add(capacityField, 1, 3);

        Button submitBtn = new Button("提交");
        submitBtn.setDisable(true);

        // 异步加载所有机房ID
        HttpRequest allReq = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8080/api/lab/get"))
                .GET().build();
        httpClient.sendAsync(allReq, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.Set<Integer> ids = new java.util.HashSet<>();
                        for (com.fasterxml.jackson.databind.JsonNode lab : dataNode) {
                            if (lab.has("labId")) ids.add(lab.get("labId").asInt());
                        }
                        javafx.application.Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载机房ID失败: " + ex.getMessage()));
                    }
                });

        // 监听下拉框选中事件，自动填充文本框
        idCombo.setOnAction(event -> {
            Integer selectedId = idCombo.getValue();
            if (selectedId == null) return;
            // 异步请求该ID的机房详细信息
            HttpRequest req = HttpRequest.newBuilder()
                    .uri(URI.create(BASE_URL + "/get/" + selectedId))
                    .GET().build();
            httpClient.sendAsync(req, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                    .thenApply(HttpResponse::body)
                    .thenAccept(json -> {
                        try {
                            // 解析后端返回的机房数据
                            JsonNode node = objectMapper.readTree(json);
                            JsonNode dataNode = node.get("data");
                            if (dataNode != null && !dataNode.isNull()) {
                                String name = dataNode.get("labName").asText();
                                String location = dataNode.get("location").asText();
                                int capacity = dataNode.get("capacity").asInt();
                                // 在UI线程中设置文本框的值
                                Platform.runLater(() -> {
                                    nameField.setText(name);
                                    locationField.setText(location);
                                    capacityField.setText(String.valueOf(capacity));
                                });
                            }
                        } catch (Exception ex) {
                            Platform.runLater(() -> showAlert("加载机房详情失败: " + ex.getMessage()));
                        }
                    })
                    .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            String name = nameField.getText().trim();
            String location = locationField.getText().trim();
            String capacityStr = capacityField.getText().trim();
            if (id == null || name.isEmpty() || location.isEmpty() || capacityStr.isEmpty()) {
                showAlert("请填写所有字段");
                return;
            }
            int capacity;
            try {
                capacity = Integer.parseInt(capacityStr);
                if (capacity <= 0) {
                    showAlert("容量必须为正整数");
                    return;
                }
            } catch (Exception ex) {
                showAlert("容量必须为数字");
                return;
            }
            Lab lab = new Lab(id, name, location, capacity);
            try {
                String json = objectMapper.writeValueAsString(lab);
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(BASE_URL + "/update"))
                        .header("Content-Type", "application/json")
                        .PUT(HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(HttpResponse::body)
                        .thenAccept(resp -> showInfoDialog("修改成功！"))
                        .exceptionally(ex -> { showAlert("请求失败: " + ex.getMessage()); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 4);
        Scene scene = new Scene(grid, 350, 250);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示删除机房的窗口
     */
    public void showDeleteWindow() {
        Stage stage = new Stage();
        stage.setTitle("删除机房");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("机房ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);

        Button submitBtn = new Button("删除");
        submitBtn.setDisable(true);

        // 异步加载所有机房ID
        HttpRequest allReq = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8080/api/lab/get"))
                .GET().build();
        httpClient.sendAsync(allReq, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.List<Integer> ids = new java.util.ArrayList<>();
                        for (com.fasterxml.jackson.databind.JsonNode lab : dataNode) {
                            ids.add(lab.get("labId").asInt());
                        }
                        javafx.application.Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载机房ID失败: " + ex.getMessage()));
                    }
                });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            if (id == null) {
                showAlert("请选择要删除的机房ID");
                return;
            }
            Lab lab = new Lab();
            lab.setLabId(id);
            try {
                String json = objectMapper.writeValueAsString(lab);
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(BASE_URL + "/delete"))
                        .header("Content-Type", "application/json")
                        .method("DELETE", HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(HttpResponse::body)
                        .thenAccept(resp -> showInfoDialog("删除成功！"))
                        .exceptionally(ex -> { showAlert("请求失败: " + ex.getMessage()); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 1);
        Scene scene = new Scene(grid, 350, 150);
        stage.setScene(scene);
        stage.show();
    }

    // 工具方法：弹窗提示
    private void showAlert(String msg) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION, msg);
            alert.showAndWait();
        });
    }

    /**
     * 显示标准信息弹窗
     * @param msg 提示信息
     */
    private void showInfoDialog(String msg) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText(null);
            alert.setContentText(msg);
            alert.showAndWait();
        });
    }
} 